<template>
  <div>
    <el-container>
      <splitpanel title="组织架构" icon="company" :request="request" :department="department" :defaultProps="defaultProps" @handleNodeClick="handleNodeClick"></splitpanel>
      <el-main class="el-mainBox">
        <el-header>
          <div class="report_header" ref="headerHeight">
            <div class="report_header_left"></div>
            <!-- <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
              <svg-icon class="primary" :icon-class="$route.meta.icon"/>
              <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
            </div> -->
            <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
              <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                         v-permission="['sysOffice.add']">新增</el-button>
            </div>
          </div>
<!--          <div>-->
<!--            <svg-icon class="primary" :icon-class="$route.meta.icon" />-->
<!--            <span class="primary">{{$route.meta.title}}</span>-->
<!--          </div>-->
<!--          <el-button v-permission="['sysOffice.add']" icon="el-icon-plus" type="primary"  @click="addClick">新增组织</el-button>-->
        </el-header>
        <div class="table-container">
          <el-table
            :data="tableData"
            style="width: 100%;margin-bottom: 20px;"
            row-key="id"
            border
            stripe
            :height="curHeight"
            v-loadMore="[payLoads,'sysOffice-list']"
            default-expand-all
            :tree-props="{children: 'childrens', hasChildren: 'hasChildren'}"
          >
            <el-table-column
              fixed="left"
              prop="name"
              label="组织名称"
              sortable
              width="250"
            />
            <el-table-column
              prop="leader"
              label="负责人"
              align="center"
              width="90"
            />
            <el-table-column
              prop="phone"
              label="办公电话"
              align="center"
              width="140"
            />
            <el-table-column
              prop="email"
              label="电子邮箱"
              align="center"
              width="140"
            />
            <el-table-column
              prop="address"
              label="联系地址"
              width="300"
            />
            <el-table-column
              prop="status"
              label="状态"
              align="center"
              width="100">
              <template slot-scope="{row}">
                <el-tag :type="row.status | statusTagFilter">
                  {{ row.status | watchStatus}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              label="备注"
            />
            <el-table-column
              prop="remark"
              label="功能"
              width="80"
              align="center"
              fixed="right"
            >
            <template slot-scope="scope">
              <el-tooltip v-permission="['sysOffice.add']" class="item" effect="dark" content="新增" placement="top-start">
                <el-button @click="addClick(scope.row)" type="primary" size="mini">新增</el-button>
              </el-tooltip>
            </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="80">
              <template slot-scope="scope">
                <div style="display: flex;flex-direction: row;justify-content: center">
                <el-tooltip v-permission="['sysOffice.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                  <a  @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit"></i>
                  </a>
                </el-tooltip>
                <el-tooltip v-permission="['sysOffice.del']" class="item" effect="dark" content="删除" placement="top-start">
                  <a style="margin-left: 10px"  @click="delSysOffice(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete"></i>
                  </a>
                </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<style scoped>
  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .table-container {
    padding: 10px;
    box-sizing: border-box;
  }
  .el-mainBox{
    padding: 0 !important;
  }
</style>
<script>
  import loadMore from '@/utils/loadMore.js'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import { EventBus } from '@/api/eventBus'
  import utils from '../../utils/utils.js'
  import { list, del } from '@/api/sysOffice'
  import splitpanel from '@/components/SplitPanel'
  export default {
    name:'sysOffice-list',
    directives: { permission,loadMore},
    activated() {
      this.payLoads = new Date().getTime();
    },
    filters: {
      watchStatus(val) {
        if (val == 1) {
          return '启用'
        } else {
          return '停用'
        }
      },
      statusTagFilter(val){
        if (val  == 1){
          return 'success'
        }else {
          return 'info'
        }
      }
    },
    data() {
      return {
        payLoads:'',
        tableData: [],
        department:[],
        defaultProps: {
          children: 'childrens',
          label: 'name'
        },
        currentParentId:'',
        currentId:'',
        officeId:'',
        request:'sysOffice',
        curHeight: null,
      }
    },
    components: {
      splitpanel
    },
    created() {
      const _this = this
      this.loadSysOffice()
      this.loadTree()
      EventBus.$on('sysOffice-add', res => { // 监听新增完毕
        // 更新列表数组
        if (!utils.isNull(res.parentId)) {
          let obj = utils.findTree(res.parentId, _this.tableData)
          obj.childrens.splice(0, 0,res)
          //更新左侧树结构
          let leftObj = utils.findTree(res.parentId, _this.department)
          leftObj.childrens.splice(0, 0,res)

        } else {
          // 没父节点就肯定是根结点
          _this.tableData.splice(0, 0,res)
          //更新左侧树结构
          _this.department.splice(0, 0,res)
        }
      })
      EventBus.$on('sysOffice-edit', res => { // 监听修改完毕
        // 更新列表数组
        let currentObj = utils.findTree(_this.currentId, _this.tableData)//找到当前子节点
        let currentParentObj = utils.findTree(_this.currentParentId, _this.tableData)//找到之前的父节点
        let nowParentObj = utils.findTree(res.parentId, _this.tableData)//找到现在的父节点

        //更新左侧树结构
        let leftCurrentObj = utils.findTree(_this.currentId, _this.department)//找到当前子节点
        let leftCurrentParentObj = utils.findTree(_this.currentParentId, _this.department)//找到之前的父节点
        let leftNowParentObj = utils.findTree(res.parentId, _this.department)//找到现在的父节点

        if (!utils.isNull(res.parentId)) {
          if(_this.currentParentId != res.parentId){ //代表换了父节点
            //删掉之前父节点下的子节点
            currentParentObj.childrens.forEach(function(item, index) {
              if (item.id == _this.currentId) {
                currentParentObj.childrens.splice(index, 1)
              }
            })
            leftCurrentParentObj.childrens.forEach(function(item, index) {
              if (item.id == _this.currentId) {
                leftCurrentParentObj.childrens.splice(index, 1)
              }
            })
            //循环更新数据
            for(let key in res){
              if(key != 'childrens'){
                currentObj[key] = res[key]
                leftCurrentObj[key] = res[key]
              }
            }
            //再往现在的父节点push修改好值的子节点
            nowParentObj.childrens.splice(0, 0,currentObj)
            leftNowParentObj.childrens.splice(0, 0,leftCurrentObj)
          }else {//没换父节点
            //循环更新数据
            for(let key in res){
              if(key != 'childrens'){
                currentObj[key] = res[key]
                leftCurrentObj[key] = res[key]
              }
            }
          }
        } else {
          // 没父节点就肯定是根结点
          //循环更新数据
          for(let key in res){
            if(key != 'childrens'){
              currentObj[key] = res[key]
              leftCurrentObj[key] = res[key]
            }
          }
        }
      })
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      beforeMount() {
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              this.curHeight = h - 266//减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              this.curHeight = h - 220//减去页面上固定高度height
            }
          })();
        };
      },
      comeIn(){
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220//减去页面上固定高度height
      },
      addClick(row) {
        if (utils.isNull(row)) {
          this.$router.push({
            path: '/sysOffice/add'
          })
        } else {
          this.$router.push({
            path: '/sysOffice/add',
            query: { rowData: row }
          })
        }
      },
      editClick(row) {
        const _this = this
        this.currentParentId = row.parentId;//记起当前父节点
        this.currentId = row.id;//记起当前id

        this.$store.dispatch('tagsView/delCachedView', {name:'sysOffice-edit'}).then(({ cachedViews }) => {
          _this.$router.push({
            path: '/sysOffice/edit',
            query: { id: row.id} // 因为修改要查找上级，所以把列表传过去
          })
        })

      },
      delSysOffice(row) {
        const _this = this
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(row.id).then(response => {
            console.log(response)
              // 更新列表数组
              if (!utils.isNull(row.parentId)) {
                const obj = utils.findTree(row.parentId, _this.tableData)
                obj.childrens.forEach(function(item, index) {
                  if (item.id == row.id) {
                    // 因为obj是_this.tableData取出来的，所以是同一指针，改变obj也会改变_this.tableData
                    obj.childrens.splice(index, 1)
                  }
                })
                const leftObj = utils.findTree(row.parentId, _this.department)
                leftObj.childrens.forEach(function(item, index) {
                  if (item.id == row.id) {
                    // 因为obj是_this.tableData取出来的，所以是同一指针，改变obj也会改变_this.tableData
                    leftObj.childrens.splice(index, 1)
                  }
                })
              } else {
                // 没父节点就肯定是根结点
                _this.tableData.forEach(function(item, index) {
                  if (item.id == row.id) {
                    _this.tableData.splice(index, 1)
                  }
                })
                _this.department.forEach(function(item, index) {
                  if (item.id == row.id) {
                    _this.department.splice(index, 1)
                  }
                })
              }
          }).catch(error => {

          })
        }).catch(() => {
        })
      },
      handleNodeClick(data) {
        this.officeId = data.id;
        this.loadSysOffice()
      },
      loadTree() {
        const _this = this
        list().then(response => {
          console.log(response)
          if (response.type == 'success') {
            _this.department = response.data
          } else {
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            })
          }
        }).catch(error => {
        })
      },
      loadSysOffice() {
        const _this = this
        const params = new URLSearchParams();
        params.append('officeId', this.officeId)
        list(params).then(response => {
          console.log(response)
          if (response.type == 'success') {
            _this.tableData = response.data
          } else {
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            })
          }
        }).catch(error => {
        })
      }
    }
  }
</script>
